#!/bin/bash

# 游戏服务器开发环境启动脚本

echo "🚀 启动游戏服务器开发环境..."

# 检查 Docker 是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker 未运行，请先启动 Docker"
    exit 1
fi

# 检查 Docker Compose 是否可用
if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose 未安装"
    exit 1
fi

# 创建必要的目录
echo "📁 创建必要的目录..."
mkdir -p logs
mkdir -p monitoring/grafana/dashboards
mkdir -p monitoring/grafana/provisioning/dashboards
mkdir -p monitoring/grafana/provisioning/datasources

# 停止现有容器
echo "🛑 停止现有容器..."
docker-compose down

# 清理旧数据（可选）
read -p "是否清理旧数据？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "🧹 清理旧数据..."
    docker-compose down -v
    docker system prune -f
fi

# 构建和启动服务
echo "🔨 构建和启动服务..."
docker-compose up --build -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 检查服务状态
echo "🔍 检查服务状态..."
docker-compose ps

# 显示服务信息
echo ""
echo "✅ 游戏服务器开发环境已启动！"
echo ""
echo "📊 服务访问地址："
echo "  - 主服务器: http://localhost:5000"
echo "  - API 文档: http://localhost:5000/swagger"
echo "  - 健康检查: http://localhost:5000/health"
echo "  - TCP 游戏: localhost:8080"
echo "  - KCP 战斗: localhost:8081"
echo "  - HTTP API: localhost:8082"
echo "  - WebSocket: localhost:8083"
echo ""
echo "🗄️ 数据库服务："
echo "  - PostgreSQL: localhost:5432"
echo "  - Redis: localhost:6379"
echo "  - RabbitMQ: localhost:5672 (管理界面: http://localhost:15672)"
echo "  - Consul: http://localhost:8500"
echo ""
echo "📈 监控服务："
echo "  - Prometheus: http://localhost:9090"
echo "  - Grafana: http://localhost:3000 (admin/admin)"
echo "  - Elasticsearch: http://localhost:9200"
echo "  - Kibana: http://localhost:5601"
echo ""
echo "📝 日志文件："
echo "  - 应用日志: ./logs/"
echo ""
echo "🛠️ 常用命令："
echo "  - 查看日志: docker-compose logs -f fserver"
echo "  - 停止服务: docker-compose down"
echo "  - 重启服务: docker-compose restart fserver"
echo "  - 进入容器: docker-compose exec fserver bash"
echo ""

# 显示实时日志
read -p "是否显示实时日志？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "📋 显示实时日志 (按 Ctrl+C 退出)..."
    docker-compose logs -f fserver
fi
